<template>

    <div class="work-detail">

        <!-- 顶部背景图和导航栏 -->

        <div class="header">

            <div class="background-image">

                <img :src="workDetail.workImage" alt="background">

            </div>

            <div class="status-bar">

                <div class="right-icons">

                    <span class="signal"></span>

                    <span class="wifi"></span>

                    <span class="battery"></span>

                </div>

            </div>

            <div class="nav-bar">

                <div class="left" @click="goBack">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
                    </svg>
                    <!-- <span class="back-arrow">←</span> -->


                </div>
                <div class="center">
                    <img class="avatar" :src="workDetail.avatar" :alt="workDetail.avatar">

                    <span class="username">{{ workDetail.nickname }}</span>

                    <button class="follow-btn">+关注</button>
                </div>

                <div class="right">

                    <button class="share-btn" @click="handleShare">

                        <i class="share-icon">⇱⇲</i>

                    </button>

                </div>

            </div>

        </div>



        <!-- 内容区域 -->

        <div class="content">
            <h1 class="title">{{ workDetail.workTitle }}</h1>
            <p class="content-text"> {{ workDetail.workContent }} </p>
            <!-- 下划线中间加文字 -->
            <div class="user_info">
                此内容为AI生成
            </div>
            <div class="qa-section">
                <div class="question">
                    <span class="q-icon">问</span>
                    <div class="q-content">{{ workDetail.workTitle }}</div>
                </div>
                <div class="answer">
                    <span class="a-icon">答</span>
                    <div class="a-content">{{ workDetail.workContent }}</div>
                </div>
            </div>
            <div class="post-info">
                <span class="post-time">{{ formatTime(workDetail.publishTime) }}</span>
                <span class="post-tag">{{ workDetail.categoryTag }}</span>
            </div>
            <br>
            <br>
            <div class="qa-section">
                <div class="question">
                    <span class="q-icon">问</span>
                    <div class="q-content">{{ workDetail.workTitle }}</div>
                </div>
                <div class="answer">
                    <span class="a-icon">答</span>
                    <div class="a-content">{{ workDetail.workContent }}</div>
                </div>
            </div>
            <div class="post-info">
                <span class="post-time">{{ formatTime(workDetail.publishTime) }}</span>
                <span class="post-tag">{{ workDetail.categoryTag }}</span>
            </div>
        </div>



        <!-- 底部操作栏 -->

        <div class="footer">

            <div class="actions">

                <div class="action-item" @click="handleLike">
                    <i :class="['like_icon', { 'liked': workDetail.isLiked }]">{{ workDetail.isLiked ? '❤' : '❤' }}</i>
                    <span class="count">{{ workDetail.likeCount }}</span>
                </div>

                <div class="action-item" @click="handleShare">
                    <i :class="['share-icon', { 'shared': workDetail.isShared }]">↗</i>
                    <span class="count">{{ workDetail.shareCount }}</span>
                </div>

            </div>
            <button class="chat-btn" @click="handleChat">我也要聊</button>

        </div>

    </div>

</template>



<script setup lang="ts">

import { ref, onMounted } from 'vue'

import { useRoute, useRouter } from 'vue-router'

import axios from 'axios'



interface WorkDetail {

    workId: number

    userId: number

    workTitle: string

    workContent: string

    workImage: string

    publishTime: string

    likeCount: number

    shareCount: number

    reviewStatus: string

    categoryTag: string

    nickname: string

    avatar: string

    isLiked: boolean

    isRequesting: boolean

    isShared: boolean


}



const route = useRoute()

const router = useRouter()



const workDetail = ref<WorkDetail>({

    workId: 0,

    userId: 0,

    workTitle: '',

    workContent: '',

    workImage: '',

    publishTime: '',

    likeCount: 0,

    shareCount: 0,

    reviewStatus: '',

    categoryTag: '',

    nickname: '',

    avatar: '',

    isLiked: false,

    isRequesting: false,

    isShared: false

})



const fetchWorkDetail = async () => {
    try {
        const workId = Number(route.params.id)
        if (isNaN(workId)) {
            throw new Error('Invalid workId parameter')
        }
        const response = await axios.get(`http://localhost:10086/commity/works/getAllWorks/${workId}`)
        if (response.status === 200) {
            const data = response.data
            // 从localStorage读取点赞状态
            const storedLikedStatus = localStorage.getItem(`post_${workId}_liked`)
            const isLiked = storedLikedStatus ? JSON.parse(storedLikedStatus) : false
            // 从localStorage读取分享状态
            const storedSharedStatus = localStorage.getItem(`post_${workId}_shared`);
            const isShared = storedSharedStatus ? JSON.parse(storedSharedStatus) : false;
            workDetail.value = {
                ...data,
                likeCount: data.likeCount || 0,
                shareCount: data.shareCount || 0,
                isLiked,
                isRequesting: false,
                isShared
            }
        } else {
            throw new Error(`HTTP error! status: ${response.status}`)
        }
    } catch (error) {
        if (error instanceof Error) {
            console.error('Error fetching work detail:', error.message)
        } else {
            console.error('Error fetching work detail:', error)
        }
    }
}



const formatTime = (time: string) => {

    if (!time) return ''

    return new Date(time).toLocaleString()

}



const goBack = () => {

    router.back()

}

// 假设已经有此函数定义
const saveLikedStatusToStorage = (postId: number, isLiked: boolean) => {
    localStorage.setItem(`post_${postId}_liked`, JSON.stringify(isLiked))
}

const handleLike = async () => {
    if (workDetail.value.isRequesting) return
    workDetail.value.isRequesting = true
    try {
        let response
        if (workDetail.value.isLiked) {
            response = await axios.get(`http://localhost:10086/commity/works/unlikesContent/${workDetail.value.workId}`)
        } else {
            response = await axios.get(`http://localhost:10086/commity/works/likesContent/${workDetail.value.workId}`)
        }
        if (response.status === 200) {
            if (workDetail.value.isLiked) {
                workDetail.value.likeCount--
                workDetail.value.isLiked = false
            } else {
                workDetail.value.likeCount++
                workDetail.value.isLiked = true
            }
            saveLikedStatusToStorage(workDetail.value.workId, workDetail.value.isLiked)
        }
    } catch (error) {
        console.error('点赞/取消点赞失败:', error)
    } finally {
        workDetail.value.isRequesting = false
    }

}



const handleShare = async () => {
    if (workDetail.value.isRequesting) return;
    workDetail.value.isRequesting = true;
    try {
        let response;
        if (workDetail.value.isShared) {
            // 取消分享
            response = await axios.get(`http://localhost:10086/commity/works/unsharesContent/${workDetail.value.workId}`);
            if (response.status === 200) {
                workDetail.value.shareCount--;
                workDetail.value.isShared = false;
                localStorage.setItem(`post_${workDetail.value.workId}_shared`, JSON.stringify(false));
            }
        } else {
            // 分享
            response = await axios.get(`http://localhost:10086/commity/works/sharesContent/${workDetail.value.workId}`);
            if (response.status === 200) {
                workDetail.value.shareCount++;
                workDetail.value.isShared = true;
                localStorage.setItem(`post_${workDetail.value.workId}_shared`, JSON.stringify(true));
            }
        }
    } catch (error) {
        console.error('分享/取消分享失败:', error);
    } finally {
        workDetail.value.isRequesting = false;
    }
};



const handleChat = () => {
    router.push({ path: '/index', query: { from: 'work-detail' } });
    // router.push({ name: 'Index', query: { from: 'work-detail' } })

}



onMounted(() => {

    fetchWorkDetail()

})

</script>



<style scoped>
.user_info {
    text-align: center;
    font-size: 14px;
    color: #999;
    margin-top: 10px;
    margin-bottom: 10px;
}

.like_icon {
    /* //border-radius: 20px;
    //background: #00000057; */
    cursor: pointer;
    padding: 4px 8px;
}

.liked {
    color: red;
}

.shared {
    color: #0057b7;
    /* 这里可以设置点亮后的颜色 */
}

.share-icon {
    font-size: 14px;
    /* border-radius: 20px; */
    /* background: #00000045; */
    cursor: pointer;
    /* margin-right: 10px; */
    display: inline-block;
    padding: 4px 8px;
}

.follow-btn {
    background: #007AFF;
    color: white;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    border: none;
    /* 新增样式属性，使按钮文字更居中 */
    display: flex;
    align-items: center;
    justify-content: center;
    /* 新增过渡效果，让交互更流畅 */
    transition: background-color 0.2s ease;
}

.work-detail {

    min-height: 100vh;

    background: #f8f8f8;

}



.header {

    position: relative;

    height: 200px;

    color: white;

}



.background-image {

    position: absolute;

    top: 0;

    left: 0;

    right: 0;

    bottom: 0;

    overflow: hidden;

}



.background-image img {

    width: 100%;

    height: 100%;

    object-fit: cover;

}



.background-image::after {

    content: '';

    position: absolute;

    top: 0;

    left: 0;

    right: 0;

    bottom: 0;

    background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5)) rgba(0, 0, 0, 0.5);
    /* 渐变背景 */

}



.nav-bar {

    position: relative;

    z-index: 1;

    display: flex;

    justify-content: space-between;

    align-items: center;

    padding: 16px;

}


.center {
    /* left: 50%; */
    transform: translateX(25%);
    display: flex;

    align-items: center;

    gap: 12px;


}

.left {
    position: absolute;
    width: 24px;
    height: 24px;
    cursor: pointer;
    color: white;

}



.back-arrow {

    font-size: 24px;

    cursor: pointer;

}



.avatar {

    width: 32px;

    height: 32px;

    border-radius: 50%;

    border: 2px solid white;

}



.username {

    font-size: 16px;

    font-weight: 500;

}



.content {

    position: relative;

    margin-top: -20px;

    padding: 20px;

    background: white;

    border-radius: 20px 20px 0 0;

    z-index: 2;

}



.title {

    font-size: 20px;

    font-weight: bold;

    margin-bottom: 16px;

}



.qa-section {

    margin: 20px 0;

}



.question,

.answer {

    display: flex;

    gap: 12px;

    margin-bottom: 16px;

}



.q-icon,

.a-icon {

    width: 24px;

    height: 24px;

    border-radius: 50%;

    display: flex;

    align-items: center;

    justify-content: center;

    font-size: 12px;

}



.q-icon {

    background: #f0f0f0;

    color: #666;

}



.a-icon {

    background: #e1f5fe;

    color: #0288d1;

}



.footer {
    /* position: fixed; */

    bottom: 0;

    left: 0;

    right: 0;

    display: flex;

    justify-content: space-between;

    align-items: center;

    padding: 12px 16px;

    background: white;

    border-top: 1px solid #eee;

}



.actions {

    display: flex;

    gap: 24px;

}



.action-item {

    display: flex;

    align-items: center;

    gap: 4px;

    color: #666;

}



.chat-btn {
    background: #007AFF;

    color: white;

    border: none;

    padding: 8px 24px;

    border-radius: 20px;

    font-size: 14px;
}
</style>
